package com.sleepfish.generator.service.impl;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sleepfish.common.activiti.PageResult;
import com.sleepfish.common.utils.PageParam;
import com.sleepfish.common.utils.json.JsonUtils;
import com.sleepfish.generator.domain.BpmForm;
import com.sleepfish.generator.domain.VO.form.BpmFormCreateReqVO;
import com.sleepfish.generator.domain.VO.form.BpmFormFieldRespDTO;
import com.sleepfish.generator.domain.VO.form.BpmFormPageReqVO;
import com.sleepfish.generator.domain.VO.form.BpmFormUpdateReqVO;
import com.sleepfish.generator.mapper.BpmFormMapper;
import com.sleepfish.generator.service.IBpmFormService;
import com.sleepfish.generator.util.BeanUtils;
import org.apache.commons.math3.stat.correlation.Covariance;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态表单 Service 实现类
 *
 * @author xiaochao
 */
@Service
public class BpmFormServiceImpl implements IBpmFormService {

    @Autowired
    private BpmFormMapper formMapper;

    @Override
    public Long createForm(BpmFormCreateReqVO createReqVO) {

        //检查是否有重复的字段
        this.checkFields(createReqVO.getFields());
        // 插入
        BpmForm form=new BpmForm();
        BeanUtils.copyBeanProp(form,createReqVO);
        // 返回

        List<BpmForm> list = formMapper.selectList();

        for (BpmForm bpmForm : list) {

            if (bpmForm.getRemark().equals(form.getRemark())){
                throw new Error("表单已存在");
            }
        }
        return formMapper.insert(form);
    }

    @Override
    public void updateForm(BpmFormUpdateReqVO updateReqVO) {

        this.checkFields(updateReqVO.getFields());

        // 校验存在
        this.validateFormExists(updateReqVO.getId());

        // 更新
        BpmForm bpmForm =new BpmForm();
        BeanUtils.copyBeanProp(bpmForm,updateReqVO);
        formMapper.updateById(bpmForm);
    }

    @Override
    public void deleteForm(Long id) {
        // 校验存在
        this.validateFormExists(id);
        // 删除
        formMapper.safeDelete(id);
    }



    @Override
    public BpmForm getForm(Long id) {
        return formMapper.selectById(id);
    }


    @Override
    public List<BpmForm> getFormList() {
        return formMapper.selectList();
    }

    @Override
    public List<BpmForm> getFormList(Collection<Long> ids) {
        Long[] idsList = Convert.toLongArray(ids);
        return formMapper.selectBatchIds(idsList);
    }

    @Override
    public List<BpmForm> getFormListVO(BpmForm bpmForm) {
        return formMapper.selectListVO(bpmForm);
    }

    @Override
    public PageResult<BpmForm> getFormPage(BpmFormPageReqVO pageReqVO) {
        Page<BpmForm> page = PageHelper.startPage(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        formMapper.getFormPage(pageReqVO);
        PageResult pageParam=new PageResult();
        pageParam.setList(page.getResult());
        pageParam.setTotal(page.getTotal());
        return pageParam;

    }


//
    /**
     * 校验 Field，避免 field 重复
     *
     * @param fields field 数组
     */
    private void checkFields(List<String> fields)  {
        Map<String, String> fieldMap = new HashMap<>(); // key 是 vModel，value 是 label
        ObjectMapper objectMapper = new ObjectMapper();

        for (String field : fields) {
            BpmFormFieldRespDTO fieldDTO=new BpmFormFieldRespDTO();
            try {
                if (!StrUtil.isEmpty(field)){
                    Map<String, Object> map =  objectMapper.readValue(field,new TypeReference<Map<String, Object>>() {});
                    Map<String,Object> config__ = (Map<String, Object>) map.get("__config__");
                    fieldDTO.setLabel((String) config__.get("label"));
                    fieldDTO.setVModel((String) map.get("__vModel__"));
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            Assert.notNull(fieldDTO);
            String oldLabel = fieldMap.put(fieldDTO.getVModel(), fieldDTO.getLabel());
            // 如果不存在，则直接返回
            if (oldLabel == null) {
                continue;
            }
            // 如果存在，则报错
            throw new Error("已经存在");
        }
    }

    private void validateFormExists(Long id) {
        if (formMapper.selectById(id) == null) {
            throw new Error("已经存在");
        }
    }

}
